package com.admin.client.components;

import com.admin.client.AppConstants;
import com.admin.client.locale.AdminConstants;
import com.admin.client.mvc.events.AppEvents;
import com.admin.share.model.UsuarioDTO;
import com.admin.share.services.LoginServiceAsync;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;


public class LoginDialog extends Dialog {

	protected TextField<String> userName;
	  protected TextField<String> password;
	  protected Button reset;
	  protected Button login;
	  public Status status; 
	  private LoginDialog singleton;

	  public LoginDialog() {
		singleton = this;
		final AdminConstants constants = Registry.get(AppConstants.CONSTANTS);
		
	    FormLayout layout = new FormLayout();
	    layout.setLabelWidth(90);
	    layout.setDefaultWidth(155);
	    setLayout(layout);
	    
	    setButtonAlign(HorizontalAlignment.LEFT);
	    setButtons("");
	    setIcon(IconHelper.createStyle("user"));
	    setHeading(constants.loginIniciarSesion());
	    setModal(true);
	    setBodyBorder(true);
	    setBodyStyle("padding: 8px;background: none");
	    setWidth(300);
	    setResizable(false);

	    userName = new TextField<String>();
	    userName.setMinLength(4);
	    userName.setFieldLabel(constants.loginUsuario());
	    userName.setAllowBlank(false);
	    userName.addKeyListener(new KeyListener(){
			public void componentKeyDown(ComponentEvent event){
				if(event.getKeyCode() == KeyCodes.KEY_ENTER){									
					password.focus();
				}
			}
		});
	    add(userName);

	    password = new TextField<String>();
	    password.setMinLength(3);
	    password.setPassword(true);
	    password.setFieldLabel(constants.loginClave());
	    password.setAllowBlank(false);
	    password.addKeyListener(new KeyListener(){
			public void componentKeyDown(ComponentEvent event){
				if(event.getKeyCode() == KeyCodes.KEY_ENTER){
					if(validate())
						onSubmit();
				}
			}
		});
	    add(password);

	    setFocusWidget(userName);

	  }

	  @Override
	  protected void createButtons() {
	    super.createButtons();
	    
	    final AdminConstants constants = Registry.get(AppConstants.CONSTANTS);
	    
	    status = new Status();
	    status.setBusy(constants.loginValidando());
	    status.hide();
	    status.setAutoWidth(true);
	    getButtonBar().add(status);
	    
	    getButtonBar().add(new FillToolItem());
	    
	    reset = new Button(constants.loginLimpiar());
	    reset.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	        userName.reset();
	        password.reset();
	        validate();
	        userName.focus();
	      }

	    });

	    login = new Button(constants.loginEntrar());    
	    login.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	    	  if(validate())
	    		  onSubmit();
	      }
	    });
	    
	    addButton(login);
	    addButton(reset);    
	  }

	  private void onSubmit() {
		final AdminConstants constants = Registry.get(AppConstants.CONSTANTS);
	    status.show();
	    getButtonBar().disable();
	    
		UsuarioDTO tda = new UsuarioDTO();	
		
		tda.setUsuario(userName.getValue());
		tda.setClave(password.getValue());
		
		final LoginServiceAsync ls = Registry.get(AppConstants.LOGIN_SERVICE);
		
		ls.isValidLogin(tda, new AsyncCallback<UsuarioDTO>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert(constants.errorConexion()+" " + caught.getMessage());						
			}

			@Override
			public void onSuccess(UsuarioDTO result) {
				if (result != null) {
					singleton.hide();					
					Dispatcher.forwardEvent(new AppEvent(AppEvents.Init, result));
					
//					if(!result.getErr()){
//						singleton.hide();					
//						
//						Dispatcher.forwardEvent(new AppEvent(AppEvents.Init, result));					
//						
//					}else{
//						singleton.status.hide();
//						singleton.getButtonBar().enable();				 
//						MessageBox.alert(constants.administradorConsultoriaSTI(), result.getErrMsg(), null);	
//					}
				}
				 else {
					 singleton.status.hide();
					 singleton.getButtonBar().enable();				 
					 MessageBox.alert(constants.administradorConsultoriaSTI(), constants.loginErrorMsg(), null);				 
				}
			}
			
		});	
		
	  }  


	  private Boolean validate() {
		  boolean user = userName.isValid();
		  boolean pw = password.isValid();
	    return  user && pw;
	  }

}
